package com.example.im.rxjava

import com.example.im.utils.ExceptionHandle
import com.example.im.utils.LogUtils
import io.reactivex.Observer
import io.reactivex.disposables.Disposable

abstract class RxSubscribe<T> : Observer<T> {

    private var disposable: Disposable? = null
    private var startTime: Long? = null

    abstract fun onSuccess(t: T)

    abstract fun onHint(hint: String)

    override fun onSubscribe(d: Disposable) {
        this.disposable = d
        this.startTime = System.currentTimeMillis()
        LogUtils.e("Start the subscribe")
    }

    override fun onNext(t: T) {
        onSuccess(t)
        LogUtils.e("Respond data:${t.toString()}")
    }

    override fun onError(e: Throwable) {

        val error = if (e is Exception)
            ExceptionHandle.HandleException(e) else ExceptionHandle.ResponseThrowable(e)
        onHint(error.message!!)

        disposable!!.dispose()
        LogUtils.e("Error code:${error.code},message:${error.message}")
    }

    override fun onComplete() {
        disposable!!.dispose()
        LogUtils.e("End the subscribe, handler run time: ${(System.currentTimeMillis() - startTime!!)}ms")
    }
}
